import fs from 'node:fs';
import { select, isCancel } from '@clack/prompts';

const directoriesSync = path => {
  try {
    const files = fs.readdirSync(path);
    return files.filter(file => fs.statSync(path + '/' + file).isDirectory());
  } catch (err) {
    console.error(err);
    return [];
  }
};
const initProject = name => {
  updateFile('index.html', /\/src.*ts/, `/src/projects/${name}/main.ts`);
  updateFile('.env', content => {
    const list = content.split('\n');
    const i = list.findIndex(option => option.startsWith('VITE_APPNAME'));
    if (i > -1) {
      list[i] = `VITE_APPNAME=${name}`;
    } else {
      list.push(`VITE_APPNAME=${name}`);
    }
    return list.join('\n');
  });
};
const updateFile = (file, ...params) => {
  let text = fs.readFileSync(file, 'utf-8');
  if (typeof params[0] === 'function') {
    text = params[0](text);
  } else if (typeof params[0] === 'object') {
    text = text.replace(params[0], params[1]);
  }
  fs.writeFileSync(file, text, 'utf-8');
};
(async () => {
  const projectList = directoriesSync('./src/projects');
  const projectName = await select({
    message: '请选择项目',
    options: projectList.map(file => ({ label: file, value: file }))
  });
  if (isCancel(projectName)) {
    return process.exit(0);
  }
  initProject(projectName);
})();
